import { getPath } from '../utils/getPath'
import { getErrors } from './getErr'
import { lazyReportCache } from '../report'

/**
 * 监听原生js报错
 */
export function onVanillaError() {

  window.addEventListener('error', event => {
    const target = event.target
    const path = getPath()
    // 例如: 加载图片报错
    if (target && (target.src || target.href)) {
      const data = {
        errorType: 'resourceError',
        filename: target.src || target.href,
        tagName: target.tagName,
        message: `加载${target.tagName}失败`,
        path
      }
      lazyReportCache('error', data)
    }
    // js运行报错
    else {
      const stack = event.error.stack
      const [err] = getErrors(stack)
      
      const data = {
        errorType: 'jsError',
        filename: err.filename,
        functionName: err.functionName,
        lineno: err.lineno,
        colno: err.colno,
        message: event.message,
        stack,
        path
      }
      lazyReportCache('error', data)
    }

  }, true)
  // promise 报错
  window.addEventListener('unhandlerejection', event => {
    const reason = event.reason
    const stack = reason.stack
    const [err] = getErrors(stack)
    const path = getPath()

    const data = {
      errorType: 'promiseError',
      filename: err.filename,
      functionName: err.functionName,
      lineno: err.lineno,
      colno: err.colno,
      message: reason.message,
      stack,
      path
    }

    lazyReportCache('error', data)
  })
}